package algorithm.leetcode.testcase;

import java.util.concurrent.*;

/**
 * FutureTask实现计时器功能
 * 等待一个任务n秒,若n秒内该任务完成不了则退出赋空值
 */

public class WaitLimit {

    static ExecutorService es = Executors.newSingleThreadExecutor();

    static class MyCall implements Callable<String> {

        String memberId;

        public MyCall(String memberId) {
            this.memberId = memberId;
        }

        @Override
        public String call() throws Exception {
            Thread.sleep(500L);
            return "s"+memberId;
        }
    }


    public static void main(String[] args) throws InterruptedException, TimeoutException {
        String s;

        Callable<String> call2 = new MyCall("1234");
        FutureTask<String> ft = new FutureTask<>(call2);
        try {
            es.submit(ft);
            s = ft.get(1000L, TimeUnit.MILLISECONDS);
        } catch (TimeoutException | ExecutionException e) {
            s = "超时赋值";
        }

        System.out.println(s);
        es.shutdown();

    }
}
